package com.zzy.service;

import com.zzy.dao.CodeDao;
import model.AutoCode;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;

import java.util.Date;
import java.util.List;

/**
 * @Author: zhangzhenyu
 * @Date: 2021/1/22
 */
@Service
public class CodeServiceImpl implements CodeService{


    @Autowired
    private CodeDao  codeDao;
    @Reference
    private EmailService emailService;
    @Override
    public Boolean create(String email) {
        AutoCode autoCode=new AutoCode();
        autoCode.setEmail(email);
        autoCode.setCreatetime(new Date());
        codeDao.saveAndFlush(autoCode);
        int code = randomCode();
        boolean b = emailService.sendEmail(email, code + "");


        return b;
    }

    @Override
    public int validate(String email, String code) {

        AutoCode resume = new AutoCode();
        resume.setEmail(email);
        resume.setCode(code);
        Example<AutoCode> example = Example.of(resume);
        List<AutoCode> autoCodes = codeDao.findAll(example);
        if (autoCodes.size()==0){
            return 1;
        }else {
            if (autoCodes.get(0).getExpiretime().getTime()<System.currentTimeMillis()){
                return 2;
            }else {
                return 0;
            }
        }


    }



    /**
     * 生成6位随机数
     */
    public static int randomCode() {
        return (int) ((Math.random() * 9 + 1) * 100000);
    }
}
